﻿using System;
using System.Configuration;
using System.Data;
using System.Web.Security;
using System.Data.SqlClient;
using System.Diagnostics.Contracts;
using System.Web.UI.WebControls;

public partial class Product : System.Web.UI.Page
{
    /// <summary> 获取由查询字符串指定的商品id。 </summary>
    public int ProductId
    {
        get
        {
            if (Request.QueryString["id"] == null)
                throw new InvalidOperationException("访问本页面时应该带有名为id的查询字符串。");
            return Convert.ToInt32(Request.QueryString["id"]);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //buyButton.PostBackUrl = ResolveUrl("~/account/pay.aspx?mode=single&id=" + Id);
        productIdsField.Value = ProductId.ToString();
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (User.Identity.IsAuthenticated)
        {
            //已登录用户，则从数据库取数据看到底该商品在不在他的购物车里。
            var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
            if (connString == null)
                throw new ArgumentNullException("无法获取指定的数据库连接字符串。");

            SetLikeFuction(connString);
            SetAddToCartFuction(connString);

        }
        else
        {
            addToCartButton.Visible = true;
            addToCartButton.Enabled = false;
            addToCartButton.ToolTip = Resources.WebResources.unavailableFunctionBeforeLogin;

            likeButton.Visible = true;
            likeButton.Enabled = false;
            likeButton.ToolTip = Resources.WebResources.unavailableFunctionBeforeLogin;

            buyButton.Enabled = false;
            buyButton.ToolTip = Resources.WebResources.unavailableFunctionBeforeLogin;
        }
    }

    private void SetLikeFuction(ConnectionStringSettings connString)
    {
        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {
            connection.Open();

            string userId = Membership.GetUser().ProviderUserKey.ToString();
            SqlCommand command = new SqlCommand(
                string.Format("select * from favoriteproduct where product='{0}' and [user]='{1}'", ProductId, userId),
                connection);
            command.CommandType = System.Data.CommandType.Text;
            object obj = command.ExecuteScalar();

            if (obj == null)
                likeButton.Visible = true;
            else
                unlikeButton.Visible = true;
        }
    }

    private void SetAddToCartFuction(ConnectionStringSettings connString)
    {
        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {
            connection.Open();

            string userId = Membership.GetUser().ProviderUserKey.ToString();
            SqlCommand command = new SqlCommand(
                string.Format("select * from [Shopping Cart] where productid='{0}' and [userid]='{1}'", ProductId, userId),
                connection);
            command.CommandType = System.Data.CommandType.Text;
            object obj = command.ExecuteScalar();

            if (obj == null)
                addToCartButton.Visible = true;
            else
                removeFromCartButton.Visible = true;
        }
    }

    protected void likeButton_Click(object sender, EventArgs e)
    {
        var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
        if (connString == null)
            throw new ArgumentNullException("无法获取指定的数据库连接字符串。");

        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {
            connection.Open();
            string userId = Membership.GetUser().ProviderUserKey.ToString();

            SqlCommand command = new SqlCommand(
                string.Format("insert into favoriteproduct values ('{0}','{1}')", ProductId, userId),
                connection);
            command.CommandType = System.Data.CommandType.Text;
            int affectedRows = command.ExecuteNonQuery();
            Contract.Assert(affectedRows > 0, "数据库操作失败，该商品没有加入到数据库表中。请稍候再试。");
        }
    }
    protected void unlikeButton_Click(object sender, EventArgs e)
    {
        var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
        if (connString == null)
            throw new ArgumentNullException("无法获取指定的数据库连接字符串。");

        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {
            connection.Open();
            string userId = Membership.GetUser().ProviderUserKey.ToString();

            SqlCommand command = new SqlCommand(
                string.Format("delete from favoriteproduct where product='{0}' and [user]='{1}'", ProductId, userId),
                connection);
            command.CommandType = System.Data.CommandType.Text;
            int affectedRows = command.ExecuteNonQuery();
            Contract.Assert(affectedRows > 0, "数据库操作失败，该商品没有从数据库表中删除。请稍候再试。");
        }
    }
    protected void removeFromCartButton_Click(object sender, EventArgs e)
    {
        var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
        if (connString == null)
            throw new ArgumentNullException("无法获取指定的数据库连接字符串。");

        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {
            connection.Open();
            string userId = Membership.GetUser().ProviderUserKey.ToString();

            SqlCommand command = new SqlCommand(
                string.Format("delete from [Shopping Cart] where productid='{0}' and [userid]='{1}'", ProductId, userId),
                connection);
            command.CommandType = System.Data.CommandType.Text;
            int affectedRows = command.ExecuteNonQuery();
            Contract.Assert(affectedRows > 0, "数据库操作失败，该商品没有从数据库表中删除。请稍候再试。");
        }
    }

    protected void addToCartButton_Click(object sender, EventArgs e)
    {
        var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
        if (connString == null)
            throw new ArgumentNullException("无法获取指定的数据库连接字符串。");

        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {
            connection.Open();
            string userId = Membership.GetUser().ProviderUserKey.ToString();

            SqlCommand command = new SqlCommand(
                string.Format("insert into [Shopping Cart] values ({0},'{1}','{2}')", quantityTextBox.Text, userId, ProductId),
                connection);
            command.CommandType = System.Data.CommandType.Text;
            int affectedRows = command.ExecuteNonQuery();
            Contract.Assert(affectedRows > 0, "数据库操作失败，该商品没有加入到数据库表中。请稍候再试。");
        }
    }

    protected void shortPropertyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item)
        {
            DataRowView rv = (DataRowView)e.Item.DataItem;
            if (Convert.ToInt32(rv["discount"]) == 0)
                return;

            var originalPriceLabel = (Label)e.Item.FindControl("originalPriceLabel");
            originalPriceLabel.Text = string.Format("(Original ${0:.00}, discount {1})", rv["price"], rv["discount"]);
            originalPriceLabel.Visible = true;
        }
    }
    protected void buyButton_Click(object sender, EventArgs e)
    {
        Response.Redirect(ResolveUrl(
            string.Format("~/account/pay.aspx?pid={0}&qty={1}", ProductId, quantityTextBox.Text)));
    }
}